import logging 
import urllib

from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

import kinds

base_url = '/links'

class MainPage(webapp.RequestHandler):
	def get(self):
		self.response.headers['Content-Type'] = 'text/html'
		wave_id = self.request.get('wave_id')

		html = ''
		html += '<html><body>'
		types = [('HTML','html'),('OPML','opml')]
		for (text,url) in types:
			logging.debug(wave_id)
			html += r'<a href="%s?wave_id=%s">%s</a><br/>'%(url,urllib.quote(wave_id),text)

		html+='</body></html>'
		self.response.out.write(html)

class OPMLPage(webapp.RequestHandler):
	def get(self):
		wave_id = self.request.get('wave_id')

		self.response.headers['Content-Type'] = 'text/xml'
		opml = ''

		opml += '<?xml version="1.0"?>\n'
		opml += '<opml version="2.0">\n'
		opml += '<head>\n'
		opml += '<title>Links from wave %s</title>\n'%wave_id
		opml += '</head>\n'
		opml += '<body>\n'

		for link in url_list(wave_id):
			opml += '<outline text="%s" type = "link" url="%s"/>\n'%(link.url,link.url)

		opml += '</body>'
		opml += '</opml>'
			
		self.response.out.write(opml)

class HTMLPage(webapp.RequestHandler):
	def get(self):
		wave_id = self.request.get('wave_id')
		self.response.headers['Content-Type'] = 'text/html'
		html = ''
		html += '<html><body>'

		for link in url_list(wave_id):
			logging.debug(link.url)
			html += '<a href="%s">%s</a><br/>'%(link.url,link.url)
		html+='</body></html>'

		self.response.out.write(html)
		

def url_list(wave_id):
	links = db.Query(kinds.Link)
	links.filter('wave_id =',wave_id)
	return links


application = webapp.WSGIApplication([('%s/'%base_url, MainPage),('%s/opml'%base_url,OPMLPage),('%s/html'%base_url,HTMLPage)],debug=False)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
